/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-11 下午2:36 Created by sky
 */
package com.jade.modules.message.sms.comm;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import com.jade.framework.base.lang.OctetString;
import org.apache.commons.io.IOUtils;

/**
 * 数据输入流.
 *
 * @author sky
 * @version 1.0 13-7-11 下午2:36
 */
public class DataInputStream
        extends java.io.DataInputStream
{
    public DataInputStream(InputStream input)
    {
        super(input);
    }

    public byte[] readBytes(int len)
            throws IOException
    {
        byte[] bytes = new byte[len];
        IOUtils.readFully(this, bytes);
        return bytes;
    }

    /**
     * 读取长度
     *
     * @return
     * @throws java.io.IOException
     */
    public OctetString readOctetString(int len)
            throws IOException
    {
        return readOctetString(len, false);
    }

    /**
     * 读取字符串
     *
     * @param len
     * @param trim 是否自动Trim
     * @return
     * @throws IOException
     */
    public OctetString readOctetString(int len, boolean trim)
            throws IOException
    {
        byte[] bytes = new byte[len];
        IOUtils.readFully(this, bytes);
        int l = len;
        if (trim) {
            l = trim(bytes, len);
        }
        return new OctetString(bytes, 0, l);
    }

    /**
     * 读取指定长度的字符串
     *
     * @param len 长度
     * @return 读取的字符串．
     */
    public String readString(int len)
            throws IOException
    {
        byte[] bytes = new byte[len];
        IOUtils.readFully(this, bytes);
        int l = trim(bytes, len);
        return new String(bytes, 0, l);
    }

    public String getString(byte[] bytes)
    {
        int l = trim(bytes, bytes.length);
        return new String(bytes, 0, l);
    }

    /**
     * Trim Bytes
     *
     * @param bytes
     * @param len
     * @return 实际长度
     */
    private int trim(byte[] bytes, int len)
    {
        for (int i = 0; i < len; i++) {
            if (bytes[i] == 0) {
                return i;
            }
        }
        return len;
    }


    /**
     * 读取字符串
     *
     * @return 读取的字符串．
     */
    public String readCString()
            throws IOException
    {
        StringBuilder sb = new StringBuilder();
        int b = 0;
        while ((b = read()) != -1) {
            if (b == 0) {
                break;
            }
            sb.append((char) b);
        }
        return sb.toString();
    }

    /** Read unsigned int. */
    public long readUnsignedInt()
            throws IOException
    {
        long ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0) {
            throw new EOFException();
        }
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }
}